import router from './router';
import store from './store';
import storage from 'store';
import NProgress from 'nprogress'; // progress bar
import {
  BasicLayout,
} from '@/layouts';
import '@/components/NProgress/nprogress.less'; // progress bar custom style
import notification from 'ant-design-vue/es/notification';
import {
  setDocumentTitle,
  domTitle,
} from '@/utils/domUtil';
import {
  ACCESS_TOKEN,
} from '@/store/mutation-types';

NProgress.configure({
  showSpinner: false,
}); // NProgress Configuration

const allowList = [ 'loginAdmin' ]; // no redirect allowList
const loginRoutePath = '/user/loginAdmin';
const defaultRoutePath = '/marketManagement';
const meunHidden = []; //需导航栏独立显示的模块
import {
  routerEach,
} from '@/utils/util'; //路由隐藏遍历

router.beforeEach((to, from, next) => {
  if (!history.state || !history.state.current) {
    Object.assign({}, history.state, { current: from.fullPath });
  }

  NProgress.start(); // start progress bar
  to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${ to.meta.title } - ${ domTitle }`);
  /* has token */
  if (storage.get(ACCESS_TOKEN)) {
    // check login user.roles is null
    if (store.getters.roles.length === 0) {
      // request login userInfo
      store
        .dispatch('GetInfo')
        .then(res => {
          const roles = res.menuList || [];
          // generate dynamic router
          store.dispatch('GenerateRoutes', {
            roles,
            topath: to.path,
          }).then((info) => {
            router.addRoutes(store.getters.addRouters);
            if (info && info.path) {
              next({
                ...to,
                replace: true,
              });
            } else {
              // window.location.href=loginRoutePath;
              // next()
              next({
                ...to,
                replace: true,
              });
            }
          });
        })
        .catch(err => {
          notification.error({
            message: '错误',
            description: '用户登录失效，请重新登录',
          });
          // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
          store.dispatch('Logout').then(() => {
            window.location.href = loginRoutePath;
          });
        });
    } else {
      if (to.meta.menuId) {
        store.dispatch('btnPermission', to.meta.menuId).then(res => {
          next();
        }).catch(erro => {
          next(false);
        });
      } else {
        store.commit('SET_SHOWBACKBTN', false);
        store.commit('SET_BTN', []);
        next();
      }
    }
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next();
    } else {
      window.location.href = loginRoutePath;
      NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
});

router.afterEach(() => {
  NProgress.done(); // finish progress bar
});

router.beforeResolve((to, from, next) => {
  const ars = to.path.split('/');
  if (meunHidden.includes(ars[1])) {
    var asd = routerEach(store.getters.original, '/' + ars[1]);
    store.commit('SET_ROUTERS', asd);
  }
  next();
});